package com.dycx.api.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.dycx.common.context.UserInfoContext;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * mybatisplus自定义填充公共字段 ,即没有传的字段自动填充
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    //新增填充
    @Override
    public void insertFill(MetaObject metaObject) {
        // 获取公共字段的值
        Object createId = metaObject.getValue("createId");
        Object createName = metaObject.getValue("createName");
        Object createTime = metaObject.getValue("createTime");

        if (UserInfoContext.get().getUserId() != null) {
            //获取当前登录用户
            if (createId == null) metaObject.setValue("createId", UserInfoContext.get().getUserId());
            if (createName == null) metaObject.setValue("createName", UserInfoContext.get().getUsername());
        }

        if (UserInfoContext.get().getUserId() != null) {
            //获取当前登录用户
            if (createId == null) metaObject.setValue("createId", UserInfoContext.get().getUserId());
            if (createName == null) metaObject.setValue("createName", UserInfoContext.get().getUsername());
        }

        if (createTime == null) metaObject.setValue("createTime", LocalDateTime.now());

        updateFill(metaObject);
    }

    //更新填充
    @Override
    public void updateFill(MetaObject metaObject) {
        Object updateId = metaObject.getValue("updateId");
        Object updateName = metaObject.getValue("updateName");
        Object updateTime = metaObject.getValue("updateTime");

        if (UserInfoContext.get().getUserId() != null) {
            //获取当前登录用户
            if (updateId == null) metaObject.setValue("updateId", UserInfoContext.get().getUserId());
            if (updateName == null) metaObject.setValue("updateName", UserInfoContext.get().getUsername());
        }

        if (UserInfoContext.get().getUserId() != null) {
            //获取当前登录用户
            if (updateId == null) metaObject.setValue("updateId", UserInfoContext.get().getUserId());
            if (updateName == null) metaObject.setValue("updateName", UserInfoContext.get().getUsername());
        }

        if (updateTime == null) metaObject.setValue("updateTime", LocalDateTime.now());
    }
}
